package com.sportizz.sport.row;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Instances;
import android.provider.CalendarContract.Reminders;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.widget.WebDialog;
import com.sportizz.model.ImageLoader;
import com.sportizz.model.Player;
import com.sportizz.model.custom_marquee_text;
import com.sportizz.sport.AlertDialogManager;
import com.sportizz.sport.DatabaseAdapter;
import com.sportizz.sport.Fb_dialog_box;
import com.sportizz.sport.MainActivity;
import com.sportizz.sport.R;
import com.sportizz.sport.R.color;
import com.sportizz.sport.Setting_Act;
import com.sportizz.sport.StartActivity;
import com.sportizz.sport.Utils;


public class ChampRow implements Row {

	private final Player player;
	private final LayoutInflater inflater;
	private DatabaseAdapter mDbHelper;

	Activity act_context;
	private boolean cpress = false;
	private String country_code;
	StartActivity sa = new StartActivity();
	ImageLoader imgLoader;
	Context con;
	String champ_channel1;
	String champ_channel2;
	String champ_channel3;
	String is_team = null;
	public ProgressDialog pd;
	AlertDialog.Builder alertDialog = null;
	AlertDialogManager alert = new AlertDialogManager();
	public boolean cal_btn = true;
	public Typeface font_champ;

	public ChampRow(LayoutInflater inflater, Player player, Context _context) {
		this.inflater = inflater;
		this.player = player;
		this.act_context = (Activity) _context;
		
		this.con = _context;
		imgLoader = new ImageLoader(con.getApplicationContext());
	}

	@SuppressWarnings("static-access")
	@SuppressLint({ "NewApi", "SimpleDateFormat" })
	@Override
	public View getView(View convertView) {

		country_code = sa.GetCountryCode(act_context);
		final ViewHolder holder;
		View view;

		if (convertView == null) {
			ViewGroup viewGroup = (ViewGroup) inflater.inflate(
					R.layout.new_custom_row_champ, null);

			holder = new ViewHolder(
					(LinearLayout) viewGroup.findViewById(R.id.head_rel_team),
					(LinearLayout) viewGroup.findViewById(R.id.linear_main),
					(TextView) viewGroup.findViewById(R.id.new_champ_txt),
					(TextView) viewGroup.findViewById(R.id.new_sport_c_name),
					(ImageView) viewGroup.findViewById(R.id.image_champ),
					(TextView) viewGroup.findViewById(R.id.new_text_game),
					(TextView) viewGroup.findViewById(R.id.new_img_c_channel2),
					(TextView) viewGroup.findViewById(R.id.new_img_c_channel1),
					(TextView) viewGroup.findViewById(R.id.new_img_c_channel3),
					(Button) viewGroup.findViewById(R.id.new_btn_c_follow),
					(Button) viewGroup.findViewById(R.id.new_btn_champ_addcal),
					(Button) viewGroup.findViewById(R.id.ticket_champ),
					(RelativeLayout)viewGroup.findViewById(R.id.relativeLayout1));

			viewGroup.setTag(holder);
			view = viewGroup;
			
			Typeface sport_font = Typeface.createFromAsset(act_context.getAssets(),
					"hel57.ttf");
			
			final String[] champ_data = player.getchamp_details().split(";");
			
			LayoutParams lparams = new LayoutParams(
					   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			
			Log.d("suraj_","player.getchamp_details() = "+champ_data.length);
			
			holder.new_btn_champ_addcal.setTag(champ_data[5]);
			
			if(champ_data.length > 8)
			{
				RelativeLayout.LayoutParams adaptLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				
				holder.relativeLayout.setLayoutParams(adaptLayout);
			}
			
			
			for(int i=1;i<champ_data.length;i++)
			{
				if(champ_data[i]!=null)
				{
					if(champ_data[i].contains("date"))
					{
						String[] champ_d = champ_data[i].split(",");
						com.sportizz.model.custom_marquee_text tv=new custom_marquee_text(act_context);
//						TextView tv=new TextView(act_context);
						tv.setLayoutParams(lparams);
						tv.setText(champ_d[1]);
						tv.setTextSize(11);
						tv.setSingleLine(true);
						tv.setFocusable(true);
						tv.setFocusableInTouchMode(true);
						tv.setTypeface(sport_font);
						tv.setTextColor(Color.parseColor("#FFCC11"));
						holder.linear_main.addView(tv);
					}
					else if(champ_data[i].contains("time"))
					{
						String[] champ_d = champ_data[i].split(",");
						com.sportizz.model.custom_marquee_text tv=new custom_marquee_text(act_context);
//						TextView tv=new TextView(act_context);
						lparams.setMargins(20, 0, 0, 0);
						tv.setTextSize(11);
						tv.setTypeface(sport_font);
						tv.setSingleLine(true);
						tv.setFocusable(true);
						tv.setTextColor(Color.WHITE);
						tv.setFocusableInTouchMode(true);
						tv.setLayoutParams(lparams);
						tv.setText(champ_d[1]);
						holder.linear_main.addView(tv);
					}
					
					
				}
			}
			
		} else {
			holder = (ViewHolder) convertView.getTag();

			view = convertView;
		}

		
		Typeface sport_font = Typeface.createFromAsset(act_context.getAssets(),
				"hel57.ttf");
		
		holder.new_btn_c_follow.setTypeface(sport_font);
		holder.new_btn_champ_addcal.setTypeface(sport_font);
		holder.ticket.setTypeface(sport_font);
		
		// holder.txt_champ_name.setTypeface(font_champ);

		final String[] champ_data = player.getchamp_details().split(";");
		
		holder.new_btn_c_follow.setTag(champ_data[0]);

		if(player.getup_y_team()==true)
		{
			holder.linearlayout.setVisibility(View.GONE);
		}
		
		if (player.geti_foll() == true) {
			holder.new_btn_c_follow.setVisibility(View.INVISIBLE);
		}

		holder.new_btn_c_follow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

//				Log.d("suraj", "player Name = " + StartActivity.player_name);

				mDbHelper = new DatabaseAdapter(act_context);
				mDbHelper.open();

				StartActivity.foll_count = StartActivity.follow_count.getInt(
						"follow_count", 0);

				Log.e("suraj", "StartActivity.foll_count = "
						+ StartActivity.foll_count);

//				if (StartActivity.foll_count < StartActivity.limited_follow
//						.getInt("max_follow", 3)
//						&& StartActivity.foll_count >= 0) {
				
					String btn_name = holder.new_btn_c_follow.getText().toString();

					if (btn_name.equals("FOLLOW") == true) {
						AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

							@Override
							protected void onPostExecute(
									Void result) {
								super.onPostExecute(result);
								pd.dismiss();
								mDbHelper.close();
							}

							@Override
							protected void onPreExecute() {
								
								pd = ProgressDialog.show(
										act_context, "",
										"Following...", true);
								super.onPreExecute();
							}

							@Override
							protected Void doInBackground(
									Void... params) {
						try {
							
							final String device_id = sa
									.GetDeviceID(act_context);

							holder.new_champ_txt.setTag(champ_data[0]);

							Log.d("suraj", "Team_id =" + player.getChamp_code());
							String response1 = null;

								
								
								mDbHelper.open();
								Long insert_c = mDbHelper.insert_follow_info(
										player.getChamp_code(),
										player.getChamp_name(),
										player.getsport_code(), player.getsport(),
										null, player.getteam(),"C");
								
								
								response1 = Utils
										.getJSONString("http://sportizza.com/interface/ios_follow.php?dev_id="
												+ device_id
												+ "&iso_cd="
												+ country_code
												+ "&follow=-1&follow_cs="
												+ player.getChamp_code() + "");


							Log.w("suraj", "insert_c = " + insert_c);
							mDbHelper.close();

							if (insert_c != 0 || response1 != null) {

								Thread t = new Thread(
										new Runnable() {
											public void run() {

												act_context.runOnUiThread(new Runnable() {
													public void run() {
														
								holder.new_btn_c_follow.setText("UNFOLLOW");
								
								MainActivity.playerAll.add(player
										.getChamp_code());

								Toast.makeText(
										act_context.getApplicationContext(),
										"Added to I follow", Toast.LENGTH_SHORT)
										.show();
								// holder.progressBar_follow.setVisibility(View.INVISIBLE);

								Log.d("suraj", "follow success..");

								StartActivity.foll_count++;
								//
								SharedPreferences.Editor editor = StartActivity.follow_count
										.edit();
								editor.putInt("follow_count",
										StartActivity.foll_count);
								editor.commit();
													}
												});
											}
										});
								t.start();

							} else {
								Toast.makeText(
										act_context.getApplicationContext(),
										"Error during follow",
										Toast.LENGTH_SHORT).show();
							}

							cpress = true;
//							mDbHelper.close();

						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(act_context.getApplicationContext(),
									"Error in follow ..", Toast.LENGTH_SHORT)
									.show();

//							mDbHelper.close();

							// holder.progressBar_follow.setVisibility(View.INVISIBLE);
						}
						return null;
							}
						};
						wait.execute();
						
					} 
					
//						else if (cpress == true) {
//						Log.d("suraj", "Already follow");
//					}
//
//				} else {
//					//
//					Toast.makeText(act_context.getApplicationContext(),
//							"Reach to Maximum Follow count....",
//							Toast.LENGTH_LONG).show();
//
//					Pay_dialog_box pdb = new Pay_dialog_box(act_context);
//					pdb.show();
//				}
			}
		});

		holder.new_btn_champ_addcal.setTypeface(sport_font);

		holder.new_btn_champ_addcal.setOnClickListener(new OnClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
//				if (MainActivity.check_cal.isChecked() == true) {
				
					String date_str = (String) holder.new_btn_champ_addcal.getTag();

					Log.v("suraj", "DAte = " + date_str);

					Long start_date_mili = null;

					String title = champ_data[1] + " - "
							+ player.getChamp_name();

					SimpleDateFormat dateFormat11 = new SimpleDateFormat(
							"dd-MM-yyyy hh:mm a");

					Date date11 = null;

					try {
						date11 = dateFormat11.parse(date_str);
					} catch (ParseException e) {
						e.printStackTrace();
					}

					start_date_mili = date11.getTime();

					long begin = start_date_mili;
					long end = start_date_mili + 30 * 60 * 1000;// ending time
							
					try
					{

						String[] proj = new String[] { Instances._ID,
							Instances.BEGIN, Instances.END, Instances.EVENT_ID };

					Cursor cursor = Instances.query(
							act_context.getContentResolver(), proj, begin, end);

					cursor.moveToFirst();

					Log.v("suraj", "Cursor = " + cursor);

					Log.v("suraj", "Cursor COUNT = " + cursor.getCount());

					if (cursor.getCount() > 0) {
						String title_cal = cursor.getString(cursor
								.getColumnIndex("title"));

						if (title_cal.equals(title)) {
							Log.i("suraj",
									"Cursor = "
											+ cursor.getString(cursor
													.getColumnIndex("title")));

							Toast.makeText(act_context,
									"Already Added to Calendar..",
									Toast.LENGTH_SHORT).show();
						} else {
							Log.i("suraj",
									"Setting_Act.check_cal.isChecked() = "
											+ Setting_Act.check_cal.isChecked());

							Log.i("suraj", "Add to calendar = " + title);

							addToCalendar(act_context, player.getChamp_name(),
									champ_data[1], title,
									start_date_mili,
									start_date_mili + 30 * 60 * 1000);
							Toast.makeText(act_context, "Added to Calendar..",
									Toast.LENGTH_SHORT).show();

						}
					} else {

						Log.i("suraj", "Add to calendar = " + title);

						addToCalendar(act_context, player.getChamp_name(),
								champ_data[1], title, start_date_mili,
								start_date_mili + 30 * 60 * 1000);
						Toast.makeText(act_context, "Added to Calendar..",
								Toast.LENGTH_SHORT).show();
					}
//				} else {
//					Toast.makeText(act_context,
//							"Access Calendar is off in setting",
//							Toast.LENGTH_SHORT).show();
//				}
				}catch (Exception e) {
					e.printStackTrace();
					
					addToCalendar(act_context, player.getChamp_name(),
							champ_data[1], title,
							start_date_mili,
							start_date_mili + 30 * 60 * 1000);
					Toast.makeText(act_context, "Added to Calendar..",
							Toast.LENGTH_SHORT).show();
				}
			}

		});

//		holder.btn_fbshare_ch.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				
//				Log.e("suraj","Session =="+ Session.getActiveSession().isOpened());
//				
//				if(Session.getActiveSession().isOpened())
//				{
//					postToWall(player.getChamp_name(),player.getgametext(),player.getDate());
//				}
//				else
//				{
//					Fb_dialog_box pdb = new Fb_dialog_box(act_context);
//					pdb.show();
//				}
//				
////				String access_token1 = StartActivity.mPrefs.getString("access_token", null);
////				if (access_token1 != null) {
////					StartActivity.facebook.setAccessToken(access_token1);
////					postToWall(player.getChamp_name(),player.getgametext(),player.getDate());
////					Log.d("FB Sessions", "" + StartActivity.facebook.isSessionValid());
////				} else 
////				{
////					loginToFacebook();
////					
////				}
//				
//			}
//		});
		
		
		String champ_img_url = null;

		InputStream is1 = null;
		try {
			if (player.gettablet() == false) {
				is1 = act_context
						.getResources()
						.getAssets()
						.open("new_sports/" + player.getsport_code()
								+ ".png");
				
				if(is1==null)
				{
					is1 = act_context
							.getResources()
							.getAssets()
							.open("new_sports/GAM.png");
				}
				Bitmap res1 = BitmapFactory.decodeStream(is1);

				Log.i("suraj", "champ =" + res1);

				Bitmap output1 = Bitmap.createBitmap(res1.getWidth(),
						res1.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas canvas1 = new Canvas(output1);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, res1.getWidth(), res1.getHeight());
				RectF rectF = new RectF(rect);
				float roundPx1 = 8f;

				paint.setAntiAlias(true);
				canvas1.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas1.drawBitmap(res1, rect, rect, paint);

				holder.image_champ.setImageBitmap(output1);
				holder.image_champ.setScaleType(ScaleType.FIT_CENTER);

				champ_img_url = "" + StartActivity.get_img_location
						+ "phone/CS/" + player.getChamp_code()
						+ ".png";
				
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(champ_img_url,loader,holder.image_champ);
				
//				new imageTask(holder.image_champ).execute(champ_img_url);

			} else if (player.gettablet() == true) {
				is1 = act_context
						.getResources()
						.getAssets()
						.open("new_sports/" + player.getsport_code()
								+ ".png");

				if(is1==null)
				{
					is1 = act_context
							.getResources()
							.getAssets()
							.open("new_sports/GAM.png");
				}
				Bitmap res2 = BitmapFactory.decodeStream(is1);

				Log.i("suraj", "" + res2);

				Bitmap output1 = Bitmap.createBitmap(res2.getWidth(),
						res2.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas canvas1 = new Canvas(output1);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, res2.getWidth(), res2.getHeight());
				RectF rectF = new RectF(rect);
				float roundPx1 = 8f;

				paint.setAntiAlias(true);
				canvas1.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas1.drawBitmap(res2, rect, rect, paint);

				holder.image_champ.setImageBitmap(output1);
				holder.image_champ.setScaleType(ScaleType.FIT_CENTER);

				champ_img_url = "" + StartActivity.get_img_location
						+ "phone/CS/" + player.getChamp_code()
						+ ".png";
//				new imageTask(holder.image_champ).execute(champ_img_url);
				
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(champ_img_url,loader,holder.image_champ);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		
		if(champ_data[1]==null || champ_data[1].equalsIgnoreCase("null"))
		{
			holder.new_text_game.setText("");
		}
		else
		{
			holder.new_text_game.setText(champ_data[1]);
		}
		
		holder.new_champ_txt.setText(player.getChamp_name());
		
		holder.new_champ_txt.setTypeface(sport_font);
		holder.new_champ_txt.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

		
		Bitmap bi_result = null ;
		
		try {
			 bi_result = BitmapFactory.decodeStream(act_context
					.getResources()
					.getAssets()
					.open("sport_small/"+ player.getsport_code() + "_S.png"));
		} catch (IOException e1) {
			e1.printStackTrace();
			 try {
				bi_result = BitmapFactory.decodeStream(act_context
							.getResources()
							.getAssets()
							.open("sport_small/GAM_S.png"));
			} catch (IOException e) {
			}
		}
		
		if(bi_result==null)
		{
			holder.new_champ_txt.setCompoundDrawablesWithIntrinsicBounds( R.drawable.team_selected, 0, 0, 0);
			
			holder.new_champ_txt.setTypeface(sport_font);
			holder.new_champ_txt.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		}
		else
		{
		Bitmap	bitmap = Bitmap.createScaledBitmap(bi_result,20, 20, true);
		
		Drawable tmpDraw = (Drawable) new BitmapDrawable(act_context.getResources(),bitmap);
		
		holder.new_champ_txt.setCompoundDrawablesWithIntrinsicBounds( tmpDraw, null, null, null);
		
		
		holder.new_champ_txt.setTypeface(sport_font);
		holder.new_champ_txt.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		}
		

		holder.new_sport_c_name.setText(player.getsport());
		holder.new_sport_c_name.setTypeface(sport_font);
		holder.new_sport_c_name.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

		Log.d("suraj", "playerAll = " + MainActivity.playerAll);


		if (MainActivity.playerAll != null) {
			if (MainActivity.playerAll.contains(holder.new_btn_c_follow.getTag()
					.toString()) == true) {
				holder.new_btn_c_follow.setText("UNFOLLOW");
			} else {
				holder.new_btn_c_follow.setText("FOLLOW");
			}
		}

		Log.v("suraj", "Match Text = " + player.getgametext());

		if(player.getticket().equals("hide"))
		{
			 holder.ticket.setVisibility(View.INVISIBLE);
		}
		
		holder.ticket.setTypeface(sport_font);
		
		holder.ticket.setOnClickListener(new OnClickListener() {
	
			@Override
			public void onClick(View arg0) {
		
				if(player.getticket().equals("") || player.getticket()==null)
				{
					Toast.makeText(act_context, "Check back later..", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Fb_dialog_box pdb = new Fb_dialog_box(act_context,player.getticket());
					pdb.show();
				}
				
			}
		});
		
//		if (champ_data[2].equalsIgnoreCase("null")
//				|| champ_data[2] == null) {
//
//		} else {
//			holder.f_txt_date.setText(champ_data[2]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.f_txt_date
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//
//		if (champ_data[3].equalsIgnoreCase("null")
//				|| champ_data[3] == null) {
//			holder.f0_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.f0_txt_match.setText(champ_data[3]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.f0_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//
//		if (champ_data[5].equalsIgnoreCase("null")
//				|| champ_data[5] == null) {
//			holder.f1_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.f1_txt_match.setText(champ_data[5]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.f1_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//		
//		if (champ_data[6].equalsIgnoreCase("null")
//				|| champ_data[6] == null) {
////			holder.f0_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.s_txt_date.setText(champ_data[6]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.s_txt_date
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//		
//		if (champ_data[7].equalsIgnoreCase("null")
//				|| champ_data[7] == null) {
//			holder.s0_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.s0_txt_match.setText(champ_data[7]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.s0_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//		if (champ_data[8].equalsIgnoreCase("null")
//				|| champ_data[8] == null) {
//			holder.s1_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.s1_txt_match.setText(champ_data[8]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.s1_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//		
//		if (champ_data[9].equalsIgnoreCase("null")
//				|| champ_data[9] == null) {
//			holder.t_txt_date.setVisibility(View.GONE);
//		} else {
//			holder.t_txt_date.setText(champ_data[9]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.t_txt_date
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
//		if (champ_data[10].equalsIgnoreCase("null")
//				|| champ_data[10] == null) {
//			holder.t0_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.t0_txt_match.setText(champ_data[10]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.t0_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
		
//		if (champ_data[11].equalsIgnoreCase("null")
//				|| champ_data[11] == null) {
//			holder.t1_txt_match.setVisibility(View.GONE);
//		} else {
//			holder.t1_txt_match.setText(champ_data[3]);
////			holder.text_match.setTextColor(Color.WHITE);
//			holder.t1_txt_match
//					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
//		}
		
		String[] channel_list = champ_data[4].split(":");
		
		if (channel_list[0].equals("null")
				|| channel_list[0].equals("NONE")
				|| channel_list[0] == null) {
			holder.new_img_c_channel1.setVisibility(View.INVISIBLE);
		} else {
			holder.new_img_c_channel1.setVisibility(View.VISIBLE);
		}

		if (channel_list[1].equals("null")
				|| channel_list[1].equals("NONE")
				|| channel_list[1] == null) {
			holder.new_img_c_channel2.setVisibility(View.INVISIBLE);
		} else {
			holder.new_img_c_channel2.setVisibility(View.VISIBLE);
		}

		if (player.getchannel_code3().equals("null")
				|| player.getchannel_code3().equals("NONE")
				|| player.getchannel_code3() == null) {
			holder.new_img_c_channel3.setVisibility(View.INVISIBLE);
		} else {
			holder.new_img_c_channel3.setVisibility(View.VISIBLE);
		}

		Log.d("suraj",
				"player.getchannel_code1() = " + player.getchannel_code1());
		Log.d("suraj",
				"player.getchannel_code2() = " + player.getchannel_code2());
		Log.d("suraj",
				"player.getchannel_code3() = " + player.getchannel_code3());

		holder.new_img_c_channel1.setText(player.getchannel_code1());
		holder.new_img_c_channel2.setText(player.getchannel_code2());
		holder.new_img_c_channel3.setText(player.getchannel_code3());

		//

		// if (player.gettablet() == false) {
		//
		// Log.d("suraj", "Phone = " + player.gettablet());
		//
		//
		// champ_channel1 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code1()
		// + ".png";
		//
		// champ_channel2 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code2()
		// + ".png";
		//
		// champ_channel3 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code3()
		// + ".png";
		//
		// new imageTask_channel(holder.channel2).execute(champ_channel1);
		// new imageTask_channel(holder.channel1).execute(champ_channel2);
		// new imageTask_channel(holder.channel3).execute(champ_channel3);
		//
		// } else if (player.gettablet() == true) {
		//
		// Log.d("suraj", "tablet = " + player.gettablet());
		//
		//
		// champ_channel1 = "" + StartActivity.get_img_location
		// + "/ss/images/pad/TV/" + player.getchannel_code1()
		// + "@2x.png";
		//
		// champ_channel2 = "" + StartActivity.get_img_location
		// + "/ss/images/pad/TV/" + player.getchannel_code2()
		// + "@2x.png";
		//
		// champ_channel3 = "" + StartActivity.get_img_location
		// + "/ss/images/pad/TV/" + player.getchannel_code3()
		// + "@2x.png";
		//
		// new imageTask_channel(holder.channel2).execute(champ_channel1);
		// new imageTask_channel(holder.channel1).execute(champ_channel2);
		// new imageTask_channel(holder.channel3).execute(champ_channel3);
		//
		// }

		return view;

	}

	
/*
//	protected void loginToFacebook() {
//		  
//		  String access_token = StartActivity.mPrefs.getString("access_token", null);
//		  long expires = StartActivity.mPrefs.getLong("access_expires", 0);
//		 
//		  if (access_token != null) {
//			  StartActivity.facebook.setAccessToken(access_token);
//		 
//			  Log.d("FB Sessions", "" + StartActivity.facebook.isSessionValid());
//		  }
//		 
//		  if (expires != 0) {
//			  StartActivity.facebook.setAccessExpires(expires);
//		  }
//		 
//		  if (!StartActivity.facebook.isSessionValid()) {
//			  StartActivity.facebook.authorize(act_context,
//		     new String[] { "email", "publish_stream" },
//		     new DialogListener() {
//		 
//		      @Override
//		      public void onCancel() {
//		      }
//		 
//		      @Override
//		      public void onComplete(Bundle values) {
//		       SharedPreferences.Editor editor = StartActivity.mPrefs.edit();
//		       editor.putString("access_token",
//		    		   StartActivity.facebook.getAccessToken());
//		       editor.putLong("access_expires",
//		    		   StartActivity.facebook.getAccessExpires());
//		       editor.commit();
//		 
//		       postToWall(player.getChamp_name(),player.getsport(),player.getDate());
//		      }
//		 
//		      @Override
//		      public void onError(DialogError error) {
//		 
//		      }
//		 
//		      @Override
//		      public void onFacebookError(FacebookError fberror) {
//		 
//		      }
//		 
//		     });
//		  }
//	}
*/

	protected void postToWall(String champ_name, String game, String date) {
		
		String[] date_only=date.split(" ");
		
		 final Bundle postParams = new Bundle();
	     postParams.putString("name", champ_name);
	     postParams.putString("caption", game);
	     postParams.putString("description", date_only[0]);
	     postParams.putString("link", "https://play.google.com/store/apps/details?id=com.sportizz.sport&hl=en");
	     postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

	     act_context.runOnUiThread(new Runnable()
		    {
		        @Override
		        public void run() 
		        {
		            WebDialog feedDialog = new WebDialog.FeedDialogBuilder(act_context, Session.getActiveSession(), postParams).build();
		            feedDialog.show();
		        }
		    });
	 	
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public void addToCalendar(Context ctx, final String title,
			final String desc, final String tit, final long dtstart,
			final long dtend) {

		Uri eventsUri, reminderuri;

		if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 14) {
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");
			// //
			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, tit);
			event.put(Events.DESCRIPTION, "SPORTIZZA");
			event.put(Events.DTSTART, dtstart);
			event.put(Events.DTEND, dtend);
			event.put(Events.STATUS, 1);
			event.put(Events.EVENT_COLOR,Color.GREEN);
			
			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			// To Insert
			Log.v("suraj", "Event =" + TimeZone.getDefault().getID());

			Uri uri = ctx.getContentResolver().insert(
					CalendarContract.Events.CONTENT_URI, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(
					CalendarContract.Reminders.CONTENT_URI, reminders);

			Log.v("suraj", "Reminder =" + reminders);

		} else if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 8
				&& Integer.parseInt(android.os.Build.VERSION.SDK) < 14) {
			//
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");
			// //

			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, tit);
			event.put(Events.DESCRIPTION, "SPORTIZZA");
			event.put(Events.DTSTART, dtstart);
			event.put(Events.DTEND, dtend);
			event.put(Events.STATUS, 1);
			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			// To Insert
			Log.v("suraj", "Event =" + event);

			Uri uri = ctx.getContentResolver().insert(eventsUri, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(reminderuri, reminders);

			Log.v("suraj", "Reminder =" + reminders);
		}

	}

	@Override
	public int getViewType() {
		return Rowtype.CHAMP_ROW.ordinal();
	}

	private static class ViewHolder {
		final LinearLayout linearlayout;
		final LinearLayout linear_main;
		final TextView new_champ_txt;
		final TextView new_sport_c_name;
		final ImageView image_champ;
		final TextView new_text_game;
		final TextView new_img_c_channel1;
		final TextView new_img_c_channel2;
		final TextView new_img_c_channel3; 
		
		final Button new_btn_c_follow;
		final Button new_btn_champ_addcal;
		final Button ticket;
		final RelativeLayout relativeLayout;
		
		private ViewHolder(LinearLayout linearlayout,LinearLayout linear_main, TextView new_champ_txt,
				TextView new_sport_c_name, ImageView image_champ, TextView new_text_game,
				TextView new_img_c_channel1, TextView new_img_c_channel2, TextView new_img_c_channel3, Button new_btn_c_follow,
				Button new_btn_champ_addcal,Button ticket, RelativeLayout relativeLayout) {
			
			this.linearlayout = linearlayout;
			this.linear_main=linear_main;
			this.new_champ_txt =new_champ_txt;
			this.new_sport_c_name=new_sport_c_name;
			this.image_champ=image_champ;
			this.new_text_game = new_text_game;
			this.ticket=ticket;
			this.new_btn_c_follow=new_btn_c_follow;
			this.new_btn_champ_addcal=new_btn_champ_addcal;
			this.relativeLayout=relativeLayout;
			this.new_img_c_channel1=new_img_c_channel1;
			this.new_img_c_channel2=new_img_c_channel2;
			this.new_img_c_channel3=new_img_c_channel3;
			
		}

	}
/*
	private class imageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView imageView = null;

		imageTask(ImageView iv) {
			this.imageView = iv;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			try {
				return download_Image(params[0]);

			} catch (OutOfMemoryError e) {
				return null;
			}

		}

		@Override
		protected void onPostExecute(Bitmap result) {
			Bitmap output;
			Canvas canvas;
			float roundPx;

			if (result == null) {

				InputStream is = null;

				try {
					if (player.gettablet() == false) {
						is = act_context
								.getResources()
								.getAssets()
								.open("default_images/phone/"
										+ player.getsport_code() + ".png");
					} else if (player.gettablet() == true) {
						is = act_context
								.getResources()
								.getAssets()
								.open("default_images/phone/"
										+ player.getsport_code() + "@2x.png");
					}

					result = BitmapFactory.decodeStream(is);

				} catch (Exception e) {
					result = BitmapFactory.decodeResource(
							act_context.getResources(), R.drawable.ic_launcher);
				}

				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 8f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);
				imageView.setScaleType(ScaleType.FIT_CENTER);

			} else {
				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 8f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);

			}
			super.onPostExecute(result);
		}

		private Bitmap download_Image(String url) {
			// ---------------------------------------------------
			Bitmap bm = null;
			try {
				URL aURL = new URL(url);
				URLConnection conn = aURL.openConnection();
				conn.connect();
				InputStream is = conn.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				bm = BitmapFactory.decodeStream(bis);
				bis.close();
				is.close();
			} catch (Exception e) {
				Log.e("Hub", "Error getting the image from server : ");
				InputStream iss = null;
				try {
					iss = act_context
							.getResources()
							.getAssets()
							.open("default_images/phone/"
									+ player.getsport_code() + ".png");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				return BitmapFactory.decodeStream(iss);
			}

			return bm;

		}

	}
*/
	
	public int getImgLoader(String sport_code) {

		int loader = R.drawable.gam;
		
		if(sport_code.equalsIgnoreCase("AFT"))
		{
			loader = R.drawable.aft;
		}else if(sport_code.equalsIgnoreCase("POL"))
		{
			loader = R.drawable.pol;
		}else if(sport_code.equalsIgnoreCase("SWI"))
		{
			loader = R.drawable.swi;
		}else if(sport_code.equalsIgnoreCase("UFC"))
		{
			loader = R.drawable.ufc;
		}else if(sport_code.equalsIgnoreCase("BAD"))
		{
			loader = R.drawable.bad;
		}else if(sport_code.equalsIgnoreCase("BB"))
		{
			loader = R.drawable.bb;
		}else if(sport_code.equalsIgnoreCase("CRI"))
		{
			loader = R.drawable.cri;
		}else if(sport_code.equalsIgnoreCase("F1"))
		{
			loader = R.drawable.f1;
		}else if(sport_code.equalsIgnoreCase("GAM"))
		{
			loader = R.drawable.gam;
		}else if(sport_code.equalsIgnoreCase("GOL"))
		{
			loader = R.drawable.gol;
		}else if(sport_code.equalsIgnoreCase("HOC"))
		{
			loader = R.drawable.hoc;
		}else if(sport_code.equalsIgnoreCase("ICE"))
		{
			loader = R.drawable.ice;
		}else if(sport_code.equalsIgnoreCase("IND"))
		{
			loader = R.drawable.ind;
		}else if(sport_code.equalsIgnoreCase("MGP"))
		{
			loader = R.drawable.mgp;
		}else if(sport_code.equalsIgnoreCase("NAS"))
		{
			loader = R.drawable.nas;
		}else if(sport_code.equalsIgnoreCase("OLY"))
		{
			loader = R.drawable.oly;
		}else if(sport_code.equalsIgnoreCase("RUG"))
		{
			loader = R.drawable.rug;
		}else if(sport_code.equalsIgnoreCase("SBK"))
		{
			loader = R.drawable.sbk;
		}else if(sport_code.equalsIgnoreCase("SOC"))
		{
			loader = R.drawable.soc;
		}else if(sport_code.equalsIgnoreCase("SPO"))
		{
			loader = R.drawable.spo;
		}else if(sport_code.equalsIgnoreCase("SQU"))
		{
			loader = R.drawable.squ;
		}else if(sport_code.equalsIgnoreCase("TEN"))
		{
			loader = R.drawable.ten;
		}else if(sport_code.equalsIgnoreCase("V8C"))
		{
			loader = R.drawable.v8c;
		}else if(sport_code.equalsIgnoreCase("WRC"))
		{
			loader = R.drawable.wrc;
		}
		else
		{
			loader = R.drawable.gam;
		}
		return loader;
	}
}
